import React, { Component } from 'react';
import {
  Card,
  Button,
  Select,
  Table,
  Alert,
  DatePicker,
  Form,
  Row,
  Col,
  Modal,
  message,
  Tooltip,
} from 'antd';
import styles from './index.less';
import Mpagination from '../../../components/Mpagination';
import MyPopover from './pages/MyPopover';
import * as apis from '@/services/SystemMgr';
// import AuthorizedButton from '@/components/AuthorizedButton';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { confirm } = Modal;
@Form.create()
class PFetchNumber extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      contentHeight: 46,
      selectsValue: {
        sysId: '', // 系统
        regionId: '', // 区域
        cityId: '', // 城市
        projectId: '', // 项目
        stagesId: '', // 分期
        beginTime: '', // 生效开始日期
        endTime: '', // 生效结束日期
      },
      pageSize: '20',
      pages: '51',
      total: '1010',
      current: '1',
      columns: [
        {
          title: '序号',
          dataIndex: 'key',
          key: 'key',
          align: 'center',
          width: '3%',
        },
        {
          title: '区域',
          dataIndex: 'region',
          key: 'region',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '城市公司',
          dataIndex: 'cityName',
          key: 'cityName',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '项目',
          dataIndex: 'project',
          key: 'project',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '分期',
          dataIndex: 'periodization',
          key: 'periodization',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '取数系统',
          dataIndex: 'FetchNumbe',
          key: 'FetchNumbe',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '生效时间',
          dataIndex: 'time',
          key: 'time',
          width: '10%',
          render: text => (
            <Tooltip placement="topLeft" title={text}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {text}
              </div>
            </Tooltip>
          ),
        },
        {
          title: '操作',
          dataIndex: 'active',
          key: 'active',
          align: 'center',
          width: '4%',
          render: (text, record) => (
            <>
              <MyPopover
                systemData={this.state.systemData}
                recordID={record.id}
                upDate={() =>
                  this.getTableData(
                    this.state.current,
                    this.state.pageSize,
                    this.state.selectsValue,
                  )
                }
                record={record}
              />
              {/* <AuthorizedButton authority="systemConfig_Config_projectNum_delete">
                {this.state.data.length > 1 ? (
                  <Button type="link" onClick={() => this.handleDeletePrjectNum(record.id)}>
                    删除
                  </Button>
                ) : null}
              </AuthorizedButton> */}
            </>
          ),
        },
      ],
      data: [],
      systemData: [], // 系统下拉
      RegionData: [], // 区域下拉
      cityData: [], // 城市下拉
      mprojectData: [], // 项目下拉
      StagesData: [], // 分期下拉
    };
  }

  async componentDidMount() {
    // 获取区域下拉数据
    const paramsRegion = {
      apiVersion: 'v1',
    };
    const RegionData = await apis.getRegionUsingGET({ params: paramsRegion });
    if (RegionData && RegionData.code === 1) {
      this.setState({
        RegionData: RegionData.data,
      });
    }
    // 获取系统下拉数据
    const paramsSystem = {
      apiVersion: 'v1',
      typeCode: 'counting_system',
    };
    const systemData = await apis.getDictionaryByTypeCodeUsingGET({ params: paramsSystem });
    if (systemData && systemData.code === 1) {
      this.setState({
        systemData: systemData.data,
      });
    }
    // 列表数据
    this.getTableData();
  }

  // 获取城市下拉数据
  async getOrgSelectData(regionId) {
    const paramsOrg = {
      apiVersion: 'v1',
      regionId,
    };
    const cityData = await apis.getCityListUsingGET({ params: paramsOrg });
    if (cityData.code === 1) {
      this.setState({
        cityData: cityData.data,
      });
      this.props.form.setFieldsValue({
        city: cityData.data.length > 0 ? cityData.data[0].cityId : '',
      });
      this.getProjectData(cityData.data.length > 0 ? cityData.data[0].cityId : 'xxx');
    }
  }

  // 获取项目下拉数据
  async getProjectData(regionId) {
    const paramsProject = {
      regionId,
    };
    const mprojectData = await apis.getProjectUsingGET({ params: paramsProject });
    if (mprojectData.code === 1) {
      this.setState({
        mprojectData: mprojectData.data,
      });
      this.props.form.setFieldsValue({
        mproject: mprojectData.data.length > 0 ? mprojectData.data[0].projectId : '',
      });
      this.getStagesData(mprojectData.data.length > 0 ? mprojectData.data[0].projectId : 'xxx');
    }
  }

  // 获取分期下拉数据
  async getStagesData(projectId) {
    const paramsStages = {
      projectId,
    };
    const StagesData = await apis.getStagesUsingGET({ params: paramsStages });
    if (StagesData.code === 1) {
      this.setState({
        StagesData: StagesData.data,
      });
      this.props.form.setFieldsValue({
        stages: StagesData.data.length > 0 ? StagesData.data[0].stagesId : '',
      });
    }
  }

  // 获取列表数据
  async getTableData(
    current = '1',
    pageSize = '20',
    selectsValue = {
      sysId: '',
      regionId: '',
      cityId: '',
      projectId: '',
      stagesId: '',
      beginTime: '',
      endTime: '',
    },
  ) {
    const params = {
      beginTime: selectsValue.beginTime, // 生效开始日期
      endTime: selectsValue.endTime, // 生效结束日期
      countingSystemId: selectsValue.sysId, // 取数系统id
      current, // 当前第几页
      pageSize, // 每页条数
      projectId: selectsValue.projectId, // 项目id
      regionId: selectsValue.regionId, // 区域id
      cityId: selectsValue.cityId, // 城市id
      stagesId: selectsValue.stagesId, // 分期id
    };
    const data = await apis.getSysProjectFetchNumberUsingGET({ params });
    if (data && data.code === 1) {
      const arr = [];
      data.data.list.forEach((item, index) => {
        arr.push({
          key: data.data.pageSize * (data.data.current - 1) + index + 1,
          id: item.id,
          region: item.regionName,
          cityName: item.cityName,
          project: item.projectName,
          periodization: item.stagesName,
          FetchNumbe: item.countingSystemName,
          time: item.effectiveDateStr,
        });
      });
      this.setState({
        data: arr,
        pageSize: data.data.pageSize,
        pages: data.data.pages,
        total: data.data.total,
        current: data.data.current,
        loading: false,
      });
    }
  }

  // 删除项目取数
  handleDeletePrjectNum = id => {
    const self = this;
    confirm({
      title: '删除项目取数',
      content: '确认之后删除项目取数',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        apis.deleteSysProjectFetchNumberUsingDELETE({ params: { id } }).then(result => {
          if (result && result.code === 1) {
            const { selectsValue, pageSize, current } = self.state;
            message.success(result.message);
            self.getTableData(current, pageSize, selectsValue);
          } else {
            message.warning(result.message);
          }
        });
      },
    });
  };

  // 获取分页点击的页数
  handlePaginationChange = (current, pageSize) => {
    const { selectsValue } = this.state;
    this.getTableData(current, pageSize, selectsValue);
    this.setState({ data: [], loading: true });
  };

  // 修改每页参数
  onShowSizeChange = (current, pageSize) => {
    this.handlePaginationChange(current, pageSize);
  };

  // get区域id请求城市下拉
  handleRegionChange = value => {
    this.getOrgSelectData(value);
  };

  // get城市id请求项目下拉
  handleProjectChange = value => {
    this.getProjectData(value);
  };

  // get项目id请求分期下拉
  handleMprojectChange = value => {
    this.getStagesData(value);
  };

  // 查询
  handleSubmitBtnClick = e => {
    e.preventDefault();
    this.setState({ data: [], loading: true });
    const { selectsValue } = this.state;
    console.log(selectsValue, 'selectsValue');
    const { form } = this.props;
    const values = form.getFieldsValue();
    selectsValue.regionId = values.region ? values.region : '';
    selectsValue.cityId = values.city ? values.city : '';
    selectsValue.projectId = values.mproject ? values.mproject : '';
    selectsValue.stagesId = values.stages ? values.stages : '';
    selectsValue.sysId = values.system ? values.system : '';
    selectsValue.beginTime =
      values.effectiveDate && values.effectiveDate.length > 0
        ? values.effectiveDate[0].format('YYYY-MM-DD')
        : '';
    selectsValue.endTime =
      values.effectiveDate && values.effectiveDate.length > 0
        ? values.effectiveDate[1].format('YYYY-MM-DD')
        : '';
    const current = '1';
    const { pageSize } = this.state;
    this.getTableData(current, pageSize, selectsValue);
  };

  // 重置高级筛选表单
  handleFormReset = () => {
    this.props.form.resetFields();
    this.setState({
      systemData: [], // 系统下拉
      cityData: [], // 城市下拉
      mprojectData: [], // 项目下拉
      StagesData: [], // 分期下拉
      loading: true,
    });
    this.getTableData();
  };

  render() {
    const {
      RegionData,
      systemData,
      cityData,
      mprojectData,
      StagesData,
      loading,
      contentHeight,
    } = this.state;
    const { selectSerach } = this.props;
    const { getFieldDecorator } = this.props.form;
    const tableHeight = document.body.clientHeight - (contentHeight === 0 ? 244 : 290);
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
      style: { marginBottom: 0 },
    };
    return (
      <div className={styles.PFetchNumber}>
        <Form
          onSubmit={this.handleSubmitBtnClick}
          layout="horizontal"
          style={{ display: selectSerach ? 'none' : 'block' }}
        >
          <Row type="flex" justify="space-around" align="middle">
            <Col md={21} sm={24}>
              <Row>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="区域">
                    {getFieldDecorator(
                      'region',
                      {},
                    )(
                      <Select
                        showSearch
                        placeholder="请选择"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onChange={this.handleRegionChange}
                      >
                        {RegionData.map(options => (
                          <Option value={options.regionId} key={options.regionId}>
                            {options.regionName}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="城市">
                    {getFieldDecorator(
                      'city',
                      {},
                    )(
                      <Select
                        showSearch
                        placeholder="请选择"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onChange={this.handleProjectChange}
                        disabled={!cityData.length > 0}
                      >
                        {cityData.map(options => (
                          <Option
                            value={options.cityId}
                            key={options.cityId}
                            title={options.cityName}
                          >
                            {options.cityName}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="项目">
                    {getFieldDecorator(
                      'mproject',
                      {},
                    )(
                      <Select
                        showSearch
                        placeholder="请选择"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onChange={this.handleMprojectChange}
                        disabled={!mprojectData.length > 0}
                      >
                        {mprojectData.map(options => (
                          <Option value={options.projectId} key={options.projectId}>
                            {options.projectName}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="分期">
                    {getFieldDecorator(
                      'stages',
                      {},
                    )(
                      <Select
                        showSearch
                        placeholder="请选择"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        disabled={!StagesData.length > 0}
                      >
                        {StagesData.map(options => (
                          <Option value={options.stagesId} key={options.stagesId}>
                            {options.stagesName}
                          </Option>
                        ))}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="取数系统">
                    {getFieldDecorator(
                      'system',
                      {},
                    )(
                      <Select
                        showSearch
                        placeholder="请选择"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {systemData.map((options, index) => {
                          let node;
                          if (index !== 0) {
                            node = (
                              <Option value={options.dict_value} key={options.dict_value}>
                                {options.dict_name}
                              </Option>
                            );
                          }
                          return node;
                        })}
                      </Select>,
                    )}
                  </Form.Item>
                </Col>
                <Col md={8} sm={24}>
                  <Form.Item {...formItemLayout} label="生效日期">
                    {getFieldDecorator(
                      'effectiveDate',
                      {},
                    )(<RangePicker onChange={this.handleDateValueChange} />)}
                  </Form.Item>
                </Col>
              </Row>
            </Col>
            <Col md={3} sm={24} justify="space-around" align="middle">
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <Card>
          <div
            className="content"
            style={{ height: `calc(100vh - ${selectSerach ? '170px' : '274px'})` }}
          >
            <div>
              <Alert
                message="修改项目分期取数系统后，新建货值版本使用修改后的配置。"
                type="warning"
                showIcon
                closable
                afterClose={() => {
                  this.setState({
                    contentHeight: 0,
                  });
                }}
              />
              <Table
                loading={loading}
                bordered
                scroll={{ y: selectSerach ? tableHeight : tableHeight - 104 }}
                columns={this.state.columns}
                dataSource={this.state.data}
                pagination={false}
              />
            </div>

            <Mpagination
              total={this.state.total}
              pageSize={this.state.pageSize}
              current={this.state.current}
              pages={this.state.pages}
              onShowSizeChange={(current, pageSize) => this.onShowSizeChange(current, pageSize)}
              handlePaginationChange={this.handlePaginationChange}
            />
          </div>
        </Card>
      </div>
    );
  }
}
export default PFetchNumber;
